package com.crm.user.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.base.Splitter;
import com.crm.customers.dao.CustomerDao;
import com.crm.customers.model.CustomerInfo;
import com.crm.im.core.session.DefaultSessionManager;
import com.crm.im.core.session.IMSession;
import com.crm.sys.dao.SysDao;
import com.crm.sys.model.Department;
import com.crm.sys.model.Role;
import com.crm.sys.model.UserRefRole;
import com.crm.sys.service.SysService;
import com.crm.user.dao.UserDao;
import com.crm.user.dao.UserInfoDao;
import com.crm.user.model.UserAccount;
import com.crm.user.model.UserInfo;
import com.crm.user.service.UserService;
import com.crm.util.Constants;
import com.crm.util.Pager;
import com.crm.util.StringUtil;
import com.wjyup.coolq.util.CQSDK;

@Service("userService")
public class UserServiceImpl implements UserService {
	
	@Autowired
	private UserDao userDao;
	@Autowired
	private SysService sysService;
	@Autowired
	private SysDao sysDao;
	@Autowired
	private DefaultSessionManager sessionManager;
	@Autowired
	private UserInfoDao userInfoDao;
	@Autowired
	private CustomerDao customerDao;
	
	
	@Override
	public void sendMsgToQQ(Long uid,String msg){
		try{
			UserInfo  info = getUserInfo(uid);
			//Nickname 已改为qq号码
			if(info!=null&&StringUtils.isNotEmpty(info.getNickname())){
				CQSDK.sendPrivateMsg(info.getNickname(), msg);
			}
		}catch(Exception e){
			
		}
		
	}
	
	@Override
	public UserAccount validateLoginUser(UserAccount user) throws Exception {
		 
		UserAccount  userObj = userDao.getUserAccountByAccount(user);
		//UserAccount  userObj = userDao.getUserAccountInfo(user);
		if(userObj!=null){
			String password = userObj.getPassword();
			password = Constants.SECURITY.decryptString(password);
			if(password.equals(user.getPassword())){
				UserInfo userinfoObj =new UserInfo();
				userinfoObj.setUid(userObj.getId());
			UserInfo userinfo=	userDao.getUserInfo(userinfoObj);
			userinfo.setCallinglist(userDao.getCallingByuid(userObj.getId()));
			if(null!=userinfo&&userinfo.getDeptid()!=null){
				Department deptObj =new Department();
				deptObj.setId(userinfo.getDeptid());
				Department dept=sysDao.getDepartmentById(deptObj);
				userObj.setDept(dept);
			}
			userObj.setInfo(userinfo);
			} 
		}
		return userObj;
	}

	@Override
	public boolean validateUserAccount(String account) {
		boolean result = false;
		UserAccount acount = new UserAccount();
		acount.setAccount(account);
		UserAccount  userObj = userDao.getUserAccountInfo(acount);
		if(userObj!=null){
			result = true;
		}
		return result;
	}

	@Override
	public boolean saveUser(UserAccount user) {
		//验证用户是否已被占用
		if(!validateUserAccount(user.getAccount()) ){
			user.setPassword( Constants.SECURITY.encryptString(user.getPassword()));
			UserAccount  userObj =  userDao.insertUser(user);
			//判断是否生成了主键ID  生成了表示新增成功
			if(userObj!=null&&userObj.getId()!=null){
				//初始化用户基本信息表
				 UserInfo userinfo = new UserInfo();
				 userinfo.setUid(userObj.getId());
				 userinfo.setIsdel(0);
				 userinfo.setMaxcustom(300);
				 userinfo.setMaxresume(5000);
				 userDao.insertUserInfo(userinfo);
				 //整合用户对象
				 user.setInfo(userinfo);
				 //默认用户为销售 角色
				 UserRefRole role = new UserRefRole();
				 role.setUid(userObj.getId());
				 //role.setRid(2);
				 userDao.insertRoleList(role);
				return true;
			}
			
		}
		return false;
	}

	@Override
	public boolean saveUserInfo(UserInfo uinfo) {
		 int result =  userDao.updateUserInfo(uinfo);
		return result>0?true:false;
	}

	@Override
	public UserInfo getUserInfo(Long id) {
		UserInfo uobj = new  UserInfo();
		uobj.setUid(id);
		return userDao.getUserInfo(uobj);
	}

	@Override
	public UserAccount getUserAccountInfoById(Long id) {
		UserAccount u = new UserAccount();
		u.setId(id);
		UserAccount user = userDao.getUserAccountInfoById(u);
		if(user!=null&&user.getId()!=null){
			UserInfo uiObj = new UserInfo();
			uiObj.setUid(user.getId());
			UserInfo userinfo=	userDao.getUserInfo(uiObj);
			userinfo.setCallinglist(userDao.getCallingByuid(user.getId()));
			if(null!=userinfo&&userinfo.getDeptid()!=null){
				Department deptObj =new Department();
				deptObj.setId(userinfo.getDeptid());
				deptObj.setParentid(null);
				Department dept=sysDao.getDepartmentById(deptObj);
				user.setDept(dept);
			}
			user.setInfo(userinfo);
		}
		return user;
	}

	@Override
	public int updatePassword(UserAccount useraccount,String password,String upwd) {
		int result=0;
		password = Constants.SECURITY.decryptString(password);
		if(password.equals(upwd)){
			result=1;
			useraccount.setPassword( Constants.SECURITY.encryptString(useraccount.getPassword()));
			userDao.updatePassword(useraccount);
		} 
		return result;
	}

	@Override
	public Pager getUserList(UserInfo user, int pageNo, int pageSize) {
		 user.setStartsize(((pageNo-1)*pageSize));
		 user.setEndsize(pageSize);
		 List<UserInfo>  list = userDao.getUserList(user);
		 for (UserInfo userinfo : list) {
		 List<Integer>   callist=userDao.getCallingByuid(userinfo.getUid());
		 userinfo.setCallinglist(callist);
		 }
		    Pager  pager = new Pager();
			pager.setPageNo(pageNo);
			pager.setPageSize(pageSize);
			pager.setResultList(list);
		    return pager;
	}

	@Override
	public List<Role> getRole(Role role) {
		
		return userDao.getRole(role);
	}

	@Override
	public int saveRole(String uid, String rid) {
		
		Iterable<String> splitStr = Splitter.on(",").trimResults().omitEmptyStrings().split(uid);
		 for (String idStr : splitStr) {
			 if(idStr.equals("1")) {
				 continue;
			 }
			 UserAccount u = new UserAccount();
			 u.setId(Long.parseLong(idStr));
			 userDao.deleteRoleList(u);
	        }
		 for (String idStr : splitStr) {
			 if(idStr.equals("1")) {
				 continue;
			 }
			 UserRefRole ur = new UserRefRole();
			 ur.setRid(Integer.parseInt(rid));
			 ur.setUid(Long.parseLong(idStr));
			 userDao.insertRoleList(ur);
	        }
		 int result=1;
		return result;
	}

	@Override
	public UserInfo getUserByid(Long uid) {
		UserInfo info = new UserInfo();
		info.setUid(uid);
		return userDao.getUserByid(info);
	}

	@Override
	public int saveUserByid(UserInfo user) {
		return userDao.saveUserByid(user);
	}

	@Override
	public int saveCalling(String uids, String callingids) {
		Iterable<String> splitStr = Splitter.on(",").trimResults().omitEmptyStrings().split(uids);
		 for (String idStr : splitStr) {
			 userDao.deletecalling(Long.valueOf(idStr));
			 Iterable<String> splitStrcalid = Splitter.on(",").trimResults().omitEmptyStrings().split(callingids);
			 for (String calid : splitStrcalid) {
				 userDao.insertcalling(Long.valueOf(idStr),Integer.parseInt(calid));
		        }
	        } 
		 int result=1;
		return result;
	}

	@Override
	public List<Department> getDeptUserList(Department dt) {
		return sysService.getDepartmentAll();
	}

	@Override
	public List<UserInfo> getUserListByDeptId(Long deptId) {
		UserInfo u = new UserInfo();
		u.setDeptid(deptId);
		return userDao.getUserInfoListByDeptid(u);
	}

	@Override
	public int deleteUserAccount(String aids,String uid) {
		int result=0;
		Iterable<String> splitStr = Splitter.on(",").trimResults().omitEmptyStrings().split(aids);
		for (String idStr : splitStr) {
			if(Long.parseLong(idStr)==1) {
				continue;
			}
			//创建用户对象
			UserAccount ua = new UserAccount(Long.parseLong(idStr));
			//获取该用户下所有的客户
			CustomerInfo ci = new CustomerInfo();
			ci.setUid(Long.parseLong(idStr));
			List<CustomerInfo> list = customerDao.getCustomerInfoAllList(ci);
			for (CustomerInfo info : list) {
				//将所有客户全部放到公共库中
				info.setUid(null);
				info.setState(4);
				customerDao.updateCustomerState(info);
			}
			//删除用户
			userDao.deleteUser(ua);
		}
		result = 1;
		/*Iterable<String> splitStr = Splitter.on(",").trimResults().omitEmptyStrings().split(aids);
		for (String idStr : splitStr) {
			//删除
			UserAccount useraccount=new UserAccount();
			useraccount.setId(Long.valueOf(idStr));
			useraccount.setState(1);;
			result=userDao.updateUserState(useraccount);
			//将用户下的客户放到公共库
			CustomerInfo info=new CustomerInfo();
			info.setCreateuser(idStr);
			info.setState(10);
			List<CustomerInfo>  list = customerDao.getCustomerInfoAllList(info);
			
			 for (CustomerInfo infoStr : list) {
				 infoStr.setId(infoStr.getId());
				 infoStr.setState(4);
				 infoStr.setUpdateuser(uid);
	        		Log log = new Log();
	        		log.setDescription("删除用户后分配客户");
	        	    log.setContentid(infoStr.getId());
		        	log.setCategory(Constants.LOGCATEGORY.ONE);
		        	log.setCreateuser(infoStr.getUpdateuser());
		        	log.setUid(Long.parseLong(infoStr.getUpdateuser()) );
		        	result=customerService.updateCustomerState(infoStr,log);
	        }
		}
		*/
		return result;
	}

	@Override
	public List<UserInfo> getAllUser() {
		
		
		
		/*List<UserAccount> all = userService.getAllUserAccount();
		if(getLoginUser()!=null){
			
			Map map = new HashMap();
			ImUserData  us = new ImUserData();
			us.setCode("0");
			us.setMsg("");
			map.put("mine", getLoginUser());
			map.put("group", new ArrayList());
			ImFriendUserData fu = new ImFriendUserData();
			fu.setList(all);
			fu.setGroupname("默认分组");
			fu.setId(1L);
			List fuList = new ArrayList();
			fuList.add(fu);
			map.put("friend",fuList);
			"groupname": "前端码屌"
			      ,"id": 1
			      ,"online": 2
			      ,"list"
			
			us.setData(map);
			return JSONArray.toJSONString(us);
		}else{
			return JSONArray.toJSONString("");
		}
		*/
		 List<UserInfo> uinfoList =  userDao.getUserAll(new UserInfo());
		 for(UserInfo u :uinfoList){
			 //uid查询出来给ID字段 为了layim正常显示对应ID  
			 IMSession  session = sessionManager.get(String.valueOf(u.getId()));
			 if(session!=null&&StringUtils.isNotEmpty(session.getAccount())){
				 u.setStatus("online");//
			 }else{
				 if(u.getId().equals(1L)){
					IMSession newSession = new IMSession();
					UserInfo  info = getUserInfo(1L);
					newSession.setGid(StringUtil.getUUID());
					newSession.setAccount("1");
					//newSession.setName(message.get("name"));
					newSession.setName(info.getName());
					newSession.setPhotoUrl(info.getPhoto());
					newSession.setDeviceId(IMSession.CHANNEL_WINDOWS);
					newSession.setHost("127.0.0.1");
					newSession.setChannel("browse");
					newSession.setDeviceModel("Flash");
					newSession.setClientVersion("2.0.0");
					newSession.setSystemVersion("Windows10");
					newSession.setBindTime(System.currentTimeMillis());
					newSession.setPackageName("jy");
					//第一次设置心跳时间为登录时间
					newSession.setBindTime(System.currentTimeMillis());
					newSession.setHeartbeat(System.currentTimeMillis());
					sessionManager.add("1", newSession);
					u.setStatus("online");	
				 }else{
					u.setStatus("offline");
				 }
			 }
		 }
		 
		return uinfoList;
	}

	@Override
	public List<UserInfo> getAllUserListByDeptId(Long deptId) {
		
		//先查我所在部门
		Department depa = new Department();
		depa.setParentid(null);
		depa.setId(deptId);
		List<Department> list = sysDao.getDepartmentAll(depa);
		for (Department d : list) {
			//创建用户对象
			UserInfo ui = new UserInfo();
			ui.setDeptid(d.getId());
			List<UserInfo> userlist = userDao.getUserInfoListByDeptid(ui);
			d.setUserlist(userlist); 
   	     	d.setDepList(getDepartmentByPid(d.getId()));
		}
		return getUserListByDeptList(list);
	}
	
	private List<UserInfo>  getUserListByDeptList(List<Department> list){
		List<UserInfo> ulist  =new ArrayList<UserInfo>();
		for(Department dept:list){
			ulist.addAll(dept.getUserlist());
			if(dept.getDepList()!=null&&dept.getDepList().size()>0){
				ulist.addAll(getUserListByDeptList(dept.getDepList()));
			}  
		} 
		return ulist;
	}
	
	 
	
	/**
	 * 递归获取我部门下的部门id
	 * */
	private List<Department> getDepartmentByPid(Long pid){
		
		Department depa = new Department();
		depa.setParentid(pid);
		List<Department> list = sysDao.getDepartmentAll(depa);
		try{
			for (Department d : list) {
				try{
					//创建用户对象
					UserInfo ui = new UserInfo();
					ui.setDeptid(d.getId());
					List<UserInfo> userlist = userDao.getUserInfoListByDeptid(ui);
					d.setUserlist(userlist); 
		   	     	d.setDepList(getDepartmentByPid(d.getId()));
				}catch(Exception e){
					e.printStackTrace();
				}
				
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public int updateUserInfo(UserInfo ui) {
		return userInfoDao.updateUserInfo(ui);
	}

	@Override
	public int resetUserPwd(UserAccount ua) {
		ua.setPassword( Constants.SECURITY.encryptString(ua.getPassword()));
		userDao.updatePassword(ua);
		return 1;
	}

	@Override
	public List<UserInfo> getUserInfoListWithDept() {
		return userInfoDao.getUserInfoListWithDept();
	}

}
